# encoding=utf-8
'''
名称: make_summary.py
作者: 郝伟老师
功能描述：
1. 自动生成 SUMMARY.md 的内容
2. 自动建立 README.md

历史: 
2024/02/22 新建
'''

import os, io, sys


def read_title(filepath):
    # 从文本文件中读取文本内容，使用了两种编码验证，以保证正确读取。
    try:
        with open(filepath, 'r', encoding = 'utf-8') as f:
            line_no = 0
            for line in f.readlines():
                line_no += 1
                if line_no > 5:
                    break
                if line.startswith('title: '):
                    title = line[6:].strip().replace('"', '')
                    break
        # print('title:', title)
        if len(title) == 0:
            title = os.path.basename(filepath)
    except Exception:
        title = os.path.basename(filepath)
    return title

def write_file(filepath, content=''):
    try:
        with open(filepath, 'w', encoding = 'utf-8') as f:
            f.write(content)
    except Exception as ex:
            print(ex)

def traverse(lines, inpath, level=0):
    exclusives = ['_book', '.git', '.gitee', 'node_modules', 'java_code', 'scripts']
    for p in sorted(os.listdir(inpath)):
        if p in exclusives:
            continue
        curpath = os.path.join(inpath, p)
        cp = curpath.replace('\\', '/').replace('..', '.')
        if os.path.isdir(curpath):
            readme=os.path.join(curpath, "README.md")
            lines.append( "    " * level + f"* [{read_title(readme)}]({cp}/README.md)")
            if not os.path.exists(readme):
                write_file(readme)
            traverse(lines, curpath, level+1)
        elif os.path.isfile(curpath):
            if curpath.lower().endswith('.md') and level > 0 and 'README.md' not in curpath:
                lines.append("    " * level + f"* [{read_title(curpath)}]({cp})")

# 对输入目录进行遍历 
inpath = '.'
if len(sys.argv) > 1 and os.path.isdir(sys.argv[1]):
    inpath = sys.argv[1]

# 全目录遍历 
lines = []
lines.append('* [《算法设计与分析》简介](README.md)')
traverse(lines, '.')

# 输出结果
try:
    with open(os.path.join(inpath, "SUMMARY.md"), 'w', encoding = 'utf-8') as f:
        for line in lines:
            f.write(line + "\n")
            print(line)
except Exception as ex:
        print(ex)

print(os.listdir(inpath))
print(sorted(os.listdir(inpath)))